<template>
  <div class="layout-container">
    <div class="layout-container-form" style="flex-direction: column">
      <div class="layout-container-form-search">
        <el-row style="text-align: left">
          <el-col :span="24">
            <el-form label-width="90px" :inline="true">
              <el-form-item label="项目名称：">
                <el-input
                  v-model="query.project_name"
                  placeholder="请输入项目名称"
                  clearable
                  style="width: 100%"
                  @keyup.enter="getTableData(true)"
                ></el-input>
              </el-form-item>
              <el-form-item label="上线时间：">
                <el-date-picker
                  v-model="query.up_date"
                  type="datetimerange"
                  prefix-icon="el-icon-date"
                  clearable
                  range-separator="→"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="下线时间：">
                <el-date-picker
                  v-model="query.down_date"
                  type="datetimerange"
                  prefix-icon="el-icon-date"
                  clearable
                  range-separator="→"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="项目ID：">
                <el-input
                  v-model="query.project_id"
                  placeholder="请输入项目ID"
                  style="width: 100%"
                  clearable
                  @keyup.enter="getTableData(true)"
                ></el-input>
              </el-form-item>
              <el-form-item label="状态：">
                <el-select
                  v-model="query.status"
                  placeholder="请选择状态"
                  style="width: 100%"
                  clearable
                  @clear="clearStatus"
                  @change="changeStatus"
                >
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="项目类型：">
                <el-select
                  v-model="query.enum_type"
                  placeholder="请选择项目类型"
                  style="width: 100%"
                  clearable
                  @clear="clearStatus"
                  @change="changeStatus"
                >
                  <el-option
                    v-for="item in enumTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item style="width:100%;text-align:right">
                <el-button
                  style="margin-left: 8px"
                  class="search-btn"
                  @click="resetSearch"
                  >{{ $t("message.common.reset") }}</el-button
                >
                <el-button
                  type="primary"
                  class="search-btn"
                  @click="getTableData(true)"
                  >{{ $t("message.common.search") }}</el-button
                >
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      <div class="layout-container-opt">
            <!-- "0" 全部权限 1查看权限 2上传权限 3 下载权限 -->
             <div style="padding:0 20px 0 18px">
                <el-checkbox v-model="checkAll" label="1" @change="changeAll">全选</el-checkbox>
            </div>
            <el-button
              v-if="
                adminInfo.admin_type < 2 ||
                (adminInfo.admin_type === 2 &&
                  adminInfo.action_permissions &&
                  adminInfo.action_permissions.includes('2'))
              "
              type="primary"
              @click="handleBatchImport"
            >
              批量导入新项目
            </el-button>
            <el-button
              v-if="
                adminInfo.admin_type < 2 ||
                (adminInfo.admin_type === 2 &&
                  adminInfo.action_permissions &&
                  adminInfo.action_permissions.includes('2'))
              "
              @click="handleBatchUpdate"
            >
              批量修改项目数据
            </el-button>
            <el-button
              v-if="adminInfo.admin_type < 2"
              :type="selectProjectData.length > 0 ? 'primary' : ''"
              :disabled="selectProjectData.length === 0"
              :loading="exportLoading"
              @click="exportProjectData"
            >
              批量导出所选数据
            </el-button>
            <!-- <el-button
              v-if="
                adminInfo.admin_type < 2 ||
                (adminInfo.admin_type === 2 &&
                  adminInfo.action_permissions &&
                  adminInfo.action_permissions.includes('2'))
              "
              type="primary"
              @click="exportProjectAllData"
            >
              批量导出所选数据
            </el-button> -->
      </div>
    </div>
    <div class="layout-container-table">
      <Table
        ref="table"
        v-model:page="page"
        v-loading="loading"
        :showSelection="true"
        :data="tableData"
        @getTableData="getTableData"
        @selection-change="handleSelectionChange"
      >
        <el-table-column prop="sort" label="序号" width="50"/>
        <el-table-column
          prop="project_id"
          label="项目ID"
        />
        <el-table-column
          prop="title"
          label="项目名称"
          show-overflow-tooltip
        >
          <template #default="scope">{{ scope.row.title }}</template>
        </el-table-column>
        <el-table-column prop="img" label="封面图" align="center" width="120">
          <template #default="scope">
            <el-image
              v-if="scope.row.cover"
              style="width: 100px; height: auto; cursor: pointer"
              :src="scope.row.cover"
              :preview-src-list="[scope.row.cover]"
            />
            <div
              v-else
              style="color: #ccc; display: inline-block; width: 100px"
            >
              未上传
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="topic_count" label="题目数" width="80">
        </el-table-column>
        <el-table-column prop="category" label="项目分类">
        </el-table-column>
        <el-table-column
          prop="rule_value"
          label="限制"
          width="200"
        >
          <template #default="scope">
            <div>领取上限：
              <span>
              {{ scope.row.limit }}
              </span>
            </div>
            <div>领取下限：
              <span>
              {{ scope.row.lower_limit }}
              </span>
            </div>
            <div>领取CD：
              <span>
              {{ scope.row.cd }}
              </span>
            </div>
            <div>每日领取上限：
              <span>
              {{ scope.row.day_limit }}
              </span>
            </div>
            <div>每日放弃上限：
              <span>
              {{ scope.row.day_give_up_limit }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="visibility" label="项目可见设置" width="80"></el-table-column>
        <el-table-column prop="old_user_restrtction" label="老用户权限" width="80"></el-table-column>
        <el-table-column prop="new_user_restrtction" label="新用户权限" width="80"></el-table-column>


        <el-table-column
          prop="online_date_time"
          label="上线时间"
          sortable
          width="135"
        >
          <template #default="scope">
            {{ dateFormat(scope.row.online_date_time) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="offline_date_time"
          label="下线时间"
          sortable
          width="135"
        >
          <template #default="scope">
            {{ dateFormat(scope.row.offline_date_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="60">
          <template #default="scope">
            <span v-if="scope.row.status === 0">未上线</span>
            <span v-if="scope.row.status === 1">已上线</span>
            <span v-if="scope.row.status === 2">已下线</span>
          </template>
        </el-table-column>
        <!-- fixed="right" -->
        <el-table-column
          :label="$t('message.common.handle')"
          width="150"
        >
          <template #default="scope">
            <el-button
              v-if="
                adminInfo.admin_type < 2 ||
                (adminInfo.admin_type === 2 &&
                  adminInfo.action_permissions.includes('1'))
              "
              type="text"
              @click="handleOpt(scope.row, 'detail')"
            >
              {{ $t("message.common.detail") }}
            </el-button>
            <span v-else>—</span>
            <span v-if="adminInfo.admin_type === 0">
              <span v-if="scope.row.status === 1">
                <span class="split-line">|</span>
                <el-button
                  type="text"
                  @click="handleOpt(scope.row, 'off_line')"
                >
                  {{ $t("message.common.off_line") }}
                </el-button>
              </span>
              <span v-if="scope.row.status === 0 || scope.row.status === 2">
                <span class="split-line">|</span>
                <el-button type="text" @click="handleOpt(scope.row, 'on_line')">
                  {{ $t("message.common.on_line") }}
                </el-button>
              </span>
              <span>
                <span class="split-line">|</span>
                <el-button type="text" @click="handleOpt(scope.row, 'del')">
                  {{ $t("message.common.del") }}
                </el-button>
              </span>
            </span>
          </template>
        </el-table-column>
      </Table>
    </div>
    <!-- 上传文件弹出框组件 -->
    <BatchImportDialog
      v-if="uploadObj.visible"
      :visible="uploadObj.visible"
      :title="uploadObj.title"
      :uploadObj="uploadObj"
      @closeUploadDialog="closeUploadDialog"
      @refreshTable="refreshTable"
    />
  </div>
</template>

<script setup lang="ts">
import { defineComponent, ref, reactive } from "vue";
import { Page } from "@/components/table/type";
import { ElMessage, ElMessageBox } from "element-plus";
import Table from "@/components/table/index.vue";
import BatchImportDialog from "@/components/uploadFile/batchImportDialog.vue";
import {
  getProjectList,
  delProject,
  changeProjectStatus,
  exportExcel,projectExport0,projectExport1,projectExport2,
  exportAllExcel,
} from "@/api/service/project.ts";
import { dateFormat, prefix, ossPrefix } from "@/utils/index.ts";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import { ossPrefixNew } from "@/utils/index.ts";
import { del } from "@/api/table";
const router = useRouter();
const route = useRoute();
const store = useStore();
const adminInfo = reactive(store.state.user.adminInfo);

// 存储搜索用的数据
const query = reactive({
  project_name: "", // 项目名称
  up_date: [], // 上线时间
  down_date: [], // 下线时间
  project_id: "", // 项目id
  status: undefined, // 状态
  enum_type:-1,//项目类型
});
// 状态
const statusOptions = ref([
  {
    label: "未上线",
    value: 0,
  },
  {
    label: "已上线",
    value: 1,
  },
  {
    label: "已下线",
    value: 2,
  },
]);
// 状态
const enumTypeOptions = ref([
  {
    label: "全部",
    value: -1,
  },{
    label: "答主",
    value: 0,
  },{
    label: "一审",
    value: 1,
  },{
    label: "二审",
    value: 2,
  }
]);
// 分页参数, 供table使用
const page: Page = reactive({
  index: 1,
  size: 50,
  total: 0,
});
// 重置
const resetSearch = () => {
  query.project_name = ""; // 项目名称
  query.up_date = []; // 上线时间
  query.down_date = []; // 下线时间
  query.project_id = ""; // 项目id
  query.status = undefined; // 状态
  query.enum_type = -1; // 状态
  getTableData(true);
};
// 清除状态
const clearStatus = () => {
  query.status = undefined;
  getTableData(true);
};
// 状态change事件
const changeStatus = () => {
  if (query.status != "") {
    getTableData(true);
  }
};
const loading = ref(false);
const tableData = ref([]);
// 获取表格数据
// params <init> Boolean ，默认为false，用于判断是否需要初始化分页

const getParams =() => {
  return  {
    page: page.index,
    page_size: page.size,
    offline_date_time: query.down_date, // string
    enum_type: query.enum_type, // string
    online_date_time: query.up_date, // string
    project_id: query.project_id, // string
    search_text: query.project_name, // string
    status: query.status == undefined ? -1 : query.status, // integer
  };
}
const getTableData = (init: Boolean) => {
  loading.value = true;
  if (init) {
    page.index = 1;
  }
 let params = getParams()
  getProjectList(params)
    .then((res: any) => {
      let data = res.data.list;
      data.forEach((d: any) => {
        d.loading = false;
      });

      tableData.value = data;
      page.total = Number(res.data.count);
      if(checkAll.value){
          changeAll(true)
      }
    })
    .catch(() => {
      tableData.value = [];
      page.index = 1;
      page.total = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};





// 批量导入
const uploadObj = reactive({
  fileType: [".xls", ".xlsx"],
  accept: ".xls, .xlsx", // 文件上传类型
  multiple: false, // 是否支持多选
  visible: false,
  title: "",
  type:'team',
  url: "", // 批量导入用户接口地址
  downloadObj: {
    name: "",
    url: "",
  },
});
const handleBatchImport = () => {
  uploadObj.visible = true;
  uploadObj.title = "批量导入新项目";
  uploadObj.url = "/admin/project/excel/imports0";
  uploadObj.downloadObj.name = "项目导入模板.xlsx"; // excel模板名称
  uploadObj.downloadObj.url = `${ossPrefixNew}项目导入模板.xlsx`; // excel模板下载地址
};
// 关闭上传文件弹出框
const closeUploadDialog = () => {
  uploadObj.visible = false;
};

// 批量更新
const handleBatchUpdate = () => {
  uploadObj.visible = true;
  uploadObj.title = "批量修改项目数据";
  uploadObj.url = "/admin/project/excel/update";
  uploadObj.downloadObj.name = "项目更新模板.xlsx"; // excel模板名称
  uploadObj.downloadObj.url = `${ossPrefixNew}项目更新模板.xlsx`; // excel模板下载地址
};

// 导入接口成功！
const refreshTable = () => {
  ElMessage.success('操作成功！')
  getTableData(true);
  closeUploadDialog()
};

// 批量导出数
const selectProjectData = ref([]); // 勾选的数据
const selectProjectIdsData = ref([]); // 勾选的数据
const exportProjectData = () => {
  exportLoading.value = true;
  exportExcelPost(selectProjectData.value);
};
// 导出通用函数
const exportLoading = ref(false);
const exportExcelPost = (ids:any) => {
  debugger
  let data = {
    ...getParams(),
    ids: [], // array[string]
  };
  delete data.page
  delete data.page_size
  if(checkAll.value){
    delete data.ids
  }else{
    if(ids){
      data.ids = ids;
    }
  }
  let test = null
  if(!data.enum_type || data.enum_type == -1){
    test = ()=>{return projectExport0}
  }
  if(data.enum_type == 1){
    test = ()=>{return projectExport1}
  }
  if(data.enum_type == 2){
    test = ()=>{return projectExport2}
  }
  test()(data)
    .then((res: any) => {
      if (res.code === 200) {
        exportLoading.value = false;
        ElMessage.success("导出成功");
        window.open(res.data);
      }
    })
    .finally(() => {
      exportLoading.value = false;
    });
};

const exportExcelAllPost = (params: any) => {
  let data = params;
  exportAllExcel(data)
    .then((res: any) => {
      if (res.code === 200) {
        exportLoading.value = false;
        ElMessage.success("导出成功");
        window.open(res.data);
      }
    })
    .finally(() => {
      exportLoading.value = false;
    });
};


const table = ref()
const checkAll = ref(false)
const changeAll = (e:any)=>{
    console.log(checkAll.value)
    if(e){
        if(selectProjectData.value.length == tableData.value.length) return
        table.value.$refs.systemTable.toggleAllSelection()
    }else{
        selectProjectData.value = [];
        selectProjectIdsData.value = [];
        table.value.$refs.systemTable.clearSelection()
    }
}
// 勾选数据
// const selectProjectData = ref([]); // 系统id
const handleSelectionChange = (data: any) => { 
  selectProjectData.value = [];
  selectProjectIdsData.value = [];
  if(data.length){
   
    if(data.length != tableData.value.length){
      checkAll.value = false
    }
    data.forEach((item: any) => {
      selectProjectData.value.push(item.Id);
      selectProjectIdsData.value.push(item.project_id);
    });
  }
};



// // 勾选数据
// const handleSelectionChange = (data: any) => {
//   selectProjectData.value = [];
//   selectProjectIdsData.value = [];
//   data.forEach((item: any) => {
//     selectProjectData.value.push(item.Id);
//     selectProjectIdsData.value.push(item.project_id);
//   });
// };
// 操作
const handleOpt = (row: any, type: String) => {
  // 项目详情 不需要二次弹框
  if (type === "detail") {
    debugger
    store.commit("user/projectDetailInfoChange", {project_id:row.project_id});
    // console.log(store.state.user.projectDetailInfo)
    router.push({
      path: "/backstagerpzzm/projectDetail/projectDetail",
      query: {
        id: row.project_id,
        t: new Date() * 1
      },
    });
    return;
  }
  ElMessageBox.confirm(`是否确认当前操作?`, "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "success",
  })
    .then(() => {
      // 项目下线
      if (type === "off_line") {
        changeProjectStatusFun(row);
      }
      // 项目上线
      if (type === "on_line") {
        changeProjectStatusFun(row);
      }
      if (type === "edit") {
        router.push({
          path: "/backstagerpzzm/projectEdit/projectEdit",
        });
      }
      // 删除
      if (type === "del") {
        deleteFun(row.Id);
      }
    })
    .catch(() => {});
};

// 修改项目状态
const changeProjectStatusFun = (row: any) => {
  // status => 0:未上线 1:已上线 2:已线下
  let data = {
    id: row.Id,
    status: row.status === 1 ? 2 : 1,
  };
  changeProjectStatus(data).then((res: any) => {
    if (res.code === 200) {
      let message = row.status === 1 ? "下线成功" : "上线成功";
      ElMessage.success(message);
      getTableData(false);
    }
  });
};

// 删除函数
const deleteFun = (id: any) => {
  let data = {
    id,
  };
  delProject(data)
    .then((res: any) => {
      if (res.code == 200) {
        getTableData(false);
        ElMessage.success("删除成功！");
      } else {
        ElMessage.error("删除失败！");
      }
    })
    .catch(() => false);
};

getTableData(true);
</script>

<style lang="scss" scoped>
.layout-container-form {
  position: relative;
}

.layout-container-form-search {
  width: 100%;
  display: inline-block !important;
  justify-content: flex-start !important;
  .search-btn {
    margin-right: 10px;
  }
}
.layout-container-opt {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: nowrap;
  padding: 10px;
  margin-top: 10px;
}
.split-line {
  margin: 0 8px;
  color: #ccc;
}
.image-slot {
  width: 50px;
  height: 50px;
  background: #fafafa;
  color: #ccc;
  font-size: 12px;
  cursor: pointer;
}
</style>
